#!/usr/bin/env python3
"""
MAESS智能体系统主应用入口
MAESS Intelligent Agent System Main Application Entry Point
"""

import asyncio
import signal
import sys
from contextlib import asynccontextmanager
from typing import Optional

# 设置Pydantic全局配置以允许任意类型
from pydantic import BaseModel, ConfigDict
# 全局设置BaseModel的配置，允许任意类型
BaseModel.model_config = ConfigDict(arbitrary_types_allowed=True)

import uvicorn
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import JSONResponse
from loguru import logger

# 导入应用模块
from api_gateway.async_routers import async_router  # 异步路由（含 search）
from app.core.config import settings
from app.core.database import init_db, close_db, VECTOR_TYPE_AVAILABLE
from app.core.redis_client import init_redis, close_redis
from app.core.monitoring import init_monitoring, close_monitoring
from app.core.exceptions import MAESSException
from app.core.logging import setup_logging
from app.core.lifecycle import lifespan_manager
from app.services.workflow_engine import WorkflowEngine
from app.services.task_scheduler import TaskScheduler
from app.services.monitoring_service import MonitoringService
from app.services.alert_service import AlertService
from app.services.circuit_breaker_manager import CircuitBreakerManager
from app.services.distributed_lock_manager import DistributedLockManager
from app.services.search_engine_manager import SearchEngineManager
from app.services.performance_dashboard_service import PerformanceDashboardService


# 设置日志
setup_logging()

# 全局变量用于优雅关闭
shutdown_event = asyncio.Event()


def signal_handler(signum: int, frame) -> None:
    """信号处理函数"""
    logger.info(f"接收到信号 {signum}，开始优雅关闭...")
    shutdown_event.set()
    sys.exit(0)


# 注册信号处理
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    logger.info("🚀 启动 MAESS 智能体系统...")
    
    try:
        # 初始化数据库 - 使用新的异步连接池管理器
        logger.info("📊 初始化数据库连接池...")
        from app.core.database.async_db_pool import initialize_async_db_pool
        await initialize_async_db_pool()
        logger.info("📊 数据库连接池初始化完成")
        
        # 确保数据库表已创建
        logger.info("📊 初始化数据库表结构...")
        await init_db()
        logger.info("📊 数据库表结构初始化完成")
        logger.info(f"PostgreSQL连接信息: {settings.DATABASE.host}:{settings.DATABASE.port}")
        logger.info(f"PgVector支持: {'已启用' if VECTOR_TYPE_AVAILABLE else '未启用'}")
        
        # 初始化Redis
        logger.info("🔄 初始化 Redis 连接...")
        await init_redis()
        
        # 初始化监控
        logger.info("📈 初始化监控系统...")
        await init_monitoring()
        
        # 初始化服务管理器
        logger.info("⚙️ 初始化服务管理器...")
        
        # 初始化熔断器管理器
        circuit_breaker_manager = CircuitBreakerManager()
        await circuit_breaker_manager.initialize()
        app.state.circuit_breaker_manager = circuit_breaker_manager
        
        # 初始化分布式锁管理器
        distributed_lock_manager = DistributedLockManager()
        await distributed_lock_manager.initialize()
        app.state.distributed_lock_manager = distributed_lock_manager
        
        # 初始化搜索引擎管理器
        search_engine_manager = SearchEngineManager()
        await search_engine_manager.initialize()
        app.state.search_engine_manager = search_engine_manager
        
        # 初始化工作流引擎
        workflow_engine = WorkflowEngine()
        await workflow_engine.initialize()
        app.state.workflow_engine = workflow_engine
        
        # 初始化任务调度器
        task_scheduler = TaskScheduler()
        await task_scheduler.initialize()
        app.state.task_scheduler = task_scheduler
        
        # 初始化监控服务
        monitoring_service = MonitoringService()
        await monitoring_service.initialize()
        app.state.monitoring_service = monitoring_service
        
        # 初始化告警服务
        alert_service = AlertService()
        await alert_service.initialize()
        app.state.alert_service = alert_service
        
        # 初始化性能监控仪表板
        logger.info("📊 初始化性能监控仪表板...")
        performance_dashboard = PerformanceDashboardService()
        await performance_dashboard.initialize()
        app.state.performance_dashboard = performance_dashboard
        
        # 启动后台任务
        logger.info("🔄 启动后台任务...")
        lifespan_manager.start_background_tasks()
        
        logger.info("✅ MAESS 智能体系统启动完成！")
        
        yield
        
    except Exception as e:
        logger.error(f"❌ 系统启动失败: {e}")
        raise
    
    finally:
        logger.info("🛑 正在关闭 MAESS 智能体系统...")
        
        # 停止后台任务
        logger.info("⏹️ 停止后台任务...")
        await lifespan_manager.stop_background_tasks()
        
        # 关闭服务
        logger.info("🔌 关闭服务...")
        if hasattr(app.state, 'performance_dashboard'):
            await app.state.performance_dashboard.close()
        if hasattr(app.state, 'alert_service'):
            await app.state.alert_service.close()
        if hasattr(app.state, 'monitoring_service'):
            await app.state.monitoring_service.close()
        if hasattr(app.state, 'task_scheduler'):
            await app.state.task_scheduler.close()
        if hasattr(app.state, 'workflow_engine'):
            await app.state.workflow_engine.close()
        if hasattr(app.state, 'search_engine_manager'):
            await app.state.search_engine_manager.close()
        if hasattr(app.state, 'distributed_lock_manager'):
            await app.state.distributed_lock_manager.close()
        if hasattr(app.state, 'circuit_breaker_manager'):
            await app.state.circuit_breaker_manager.close()
        
        # 关闭基础设施
        logger.info("🔌 关闭基础设施...")
        await close_monitoring()
        await close_redis()
        # 关闭数据库连接池 - 使用新的异步连接池管理器
        try:
            from app.core.database.async_db_pool import close_async_db_pool
            await close_async_db_pool()
            logger.info("📊 数据库连接池已关闭")
        except Exception as e:
            logger.error(f"📊 关闭数据库连接池失败: {str(e)}")
        
        logger.info("✅ MAESS 智能体系统已关闭")


# 创建 FastAPI 应用
app = FastAPI(
    title=settings.APP_NAME,
    description="MAESS智能体系统 - 多智能体协同工作流平台",
    version=settings.APP_VERSION,
    docs_url="/api/docs",
    redoc_url="/api/redoc",
    openapi_url="/api/openapi.json",
    lifespan=lifespan
)

# 引入搜索路由
from api_gateway.routers.search import search_router


# 添加中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.add_middleware(GZipMiddleware, minimum_size=1000)


@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    """添加处理时间头部"""
    import time
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response


@app.exception_handler(MAESSException)
async def maess_exception_handler(request: Request, exc: MAESSException):
    """自定义异常处理"""
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "error": {
                "code": exc.error_code,
                "message": exc.message,
                "details": exc.details
            }
        }
    )


@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
    """通用异常处理"""
    logger.error(f"未处理的异常: {exc}")
    return JSONResponse(
        status_code=500,
        content={
            "error": {
                "code": "INTERNAL_ERROR",
                "message": "内部服务器错误",
                "details": str(exc) if settings.APP_DEBUG else None
            }
        }
    )


# 健康检查端点
@app.get("/health")
async def health_check():
    """健康检查"""
    return {
        "status": "healthy",
        "timestamp": asyncio.get_event_loop().time(),
        "version": settings.APP_VERSION,
        "services": {
            "database": await lifespan_manager.check_database_health(),
            "redis": await lifespan_manager.check_redis_health(),
            "workflow_engine": await lifespan_manager.check_workflow_engine_health(),
            "task_scheduler": await lifespan_manager.check_task_scheduler_health(),
            "performance_dashboard": await lifespan_manager.check_performance_dashboard_health()
        }
    }


# 就绪检查端点
@app.get("/ready")
async def readiness_check():
    """就绪检查"""
    return {
        "status": "ready",
        "timestamp": asyncio.get_event_loop().time(),
        "checks": await lifespan_manager.get_readiness_checks()
    }


# 存活检查端点
@app.get("/alive")
async def liveness_check():
    """存活检查"""
    return {
        "status": "alive",
        "timestamp": asyncio.get_event_loop().time(),
        "uptime": await lifespan_manager.get_uptime()
    }


# 直接注册搜索路由到/api/v1路径
app.include_router(search_router, prefix="/api/v1", tags=["搜索接口"])

# 注册系统状态路由
from api_gateway.routers.status import status_router
app.include_router(status_router, prefix="/api/v1", tags=["系统状态"])

# 注册异步API路由
app.include_router(async_router, prefix="/api/v1")


# 根路径
@app.get("/")
async def root():
    """根路径"""
    return {
        "name": settings.APP_NAME,
        "version": settings.APP_VERSION,
        "description": "MAESS智能体系统 - 多智能体协同工作流平台",
        "docs": "/api/docs",
        "health": "/health",
        "ready": "/ready",
        "alive": "/alive"
    }


def main():
    """主函数"""
    try:
        logger.info(f"启动 {settings.APP_NAME} v{settings.APP_VERSION}")
        
        # 运行应用
        uvicorn.run(
            "main:app",
            host=settings.APP_HOST,
            port=settings.APP_PORT,
            reload=settings.APP_DEBUG,
            log_level=settings.LOG_LEVEL.lower(),
            access_log=True,
            workers=1 if settings.APP_DEBUG else 4
        )
        
    except KeyboardInterrupt:
        logger.info("用户中断程序")
    except Exception as e:
        logger.error(f"应用启动失败: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()